const express = require('express');
const axios = require('axios');
const app = express();

// 设置代理，以便可以从服务器端直接请求GitHub的API
app.use('/search/users', (req, res) => {
  const query = req.query.q;
  const url = `https://api.github.com/search/users?q=${query}`;
  axios.get(url).then(
    (response) => {
      res.json(response.data);
    },
    (error) => {
      console.error('Error fetching data: ', error);
      res.status(500).send('Server error');
    }
  );
});
//gitub接口访问出错，则请求该地址
app.get('/search/users2', (request, response) => {
  // 随机生成100条用户头像数据。
  const users = Array.from({ length: 50 }, (_, i) => ({
    id: i + 1,
    avatar_url: `https://picsum.photos/200/300?random=${i}`,
    login: `User ${i + 1}`,
    html_url: 'https://github.com',
  }));
  response.json({
    items: users,
  });
});

app.listen(5000, (err) => {
  if (!err) {
    console.log(`Server running on 5000`);
  }
});
